package cn.com.bsoft.cloud.service.serviceImpl;

import cn.com.bsoft.cloud.dao.cloud.CloudAppDao;
import cn.com.bsoft.cloud.dao.cloud.ScheduleSiteDao;
import cn.com.bsoft.cloud.entity.AppointFileMess;
import cn.com.bsoft.cloud.entity.ScheduleRecord;
import cn.com.bsoft.cloud.entity.ScheduleSite;
import cn.com.bsoft.cloud.entity.ScheduleVideo;
import cn.com.bsoft.cloud.entity.cloud.*;
import cn.com.bsoft.cloud.service.CloudAppService;
import cn.com.bsoft.cloud.utils.ResultCode;
import cn.com.bsoft.immunity.kotlin.JsonExtKt;
import cn.com.bsoft.immunity.utils.HttpUtilsKt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import kotlin.jvm.internal.Reflection;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.thymeleaf.util.ListUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(value="txManagerCloud")
public class CloudAppServiceImpl implements CloudAppService{

    @Autowired
    private CloudAppDao cloudAppDao;
    @Autowired
    private ScheduleSiteDao scheduleSiteDao;

    @Override
    public List<AppointMessSec> queryDrugByYyid(String yyidstr) {
        String sqlyyid="";
        String[] yyidarray = yyidstr.split(",");
        for(int i=0;i<yyidarray.length;i++){
            if(i==0){
                sqlyyid+="'"+yyidarray[i]+"'";
            }else{
                sqlyyid+=",'"+yyidarray[i]+"'";
            }
        }
        //查询预约信息
        List<AppointMessSec> amlist=cloudAppDao.queryDrugByYyidSec(sqlyyid);
        //通过预约id查询对应的处方
        if(amlist!=null&&amlist.size()>0){
            for (AppointMessSec am:amlist) {
                List<PrescriptionMessSec> list=cloudAppDao.queryDrugDetailByYyidSec(am.getAppointId());
                am.setPrescriptionMess(list);
            }
        }
        /*//通过配送点编码查询配送地址
        String address=cloudAppDao.findAddressByCode(amlist);*/
        return amlist;
    }

    @Override
    public Map<String, Object> addAppointSite(String yyid, String psdbm, String psdmc) {
        Map<String,Object> regMsg=new HashMap<String, Object>();
        //先通过yyid查询是否已经存在yyid
        String id=cloudAppDao.findAppointId(yyid);
        if(StringUtils.isNotBlank(id)){
            regMsg.put("code", ResultCode.ERROR);
            regMsg.put("msg", "已存在预约对应的配送点信息,添加失败");
            regMsg.put("result", null);
            return regMsg;
        }
        Boolean b=cloudAppDao.addAppointSite(yyid,psdbm,psdmc);
        if(b){//添加成
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("yyid",yyid);
            map.put("pharmacyCode",psdbm);
            map.put("pharmacyName",psdmc);
            try {
                Object object = HttpUtilsKt.postJson(new URL(ResultCode.updateAppointMess), map, JsonExtKt.getJavaType(Reflection.getOrCreateKotlinClass(Object.class)));
                String json = JSON.toJSON(object).toString();
            } catch (Exception e) {
                regMsg.put("code", ResultCode.ERROR);
                regMsg.put("msg", "添加失败");
                regMsg.put("result", null);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
                return regMsg;
            }
            regMsg.put("code", ResultCode.SUCCESS);
            regMsg.put("msg", "添加成功");
            regMsg.put("result", null);
        }else{
            regMsg.put("code", ResultCode.ERROR);
            regMsg.put("msg", "添加失败");
            regMsg.put("result", null);
        }
        return regMsg;
    }


    @Override
    public List<DoctorInformation> findMessByLogname(String logName) {
        return cloudAppDao.findMessByLogname(logName);
    }

    @Override
    public List<ScheduleRecord> queryScheduleRecordEx(Map<String, String> map) {
        List<ScheduleRecord> scheduleRecords =  new ArrayList<ScheduleRecord>();
        try {
            Object object = HttpUtilsKt.postJson(new URL(ResultCode.cloudDocMess), map, JsonExtKt.getJavaType(Reflection.getOrCreateKotlinClass(Object.class)));
            String json = JSON.toJSON(object).toString();
            List<ScheduleRecord> list = JSONArray.parseArray(json, ScheduleRecord.class);
            if (list !=null && list.size() >0) {
                List<String> ids = getAppointIdS(list);
                List<ScheduleVideo> videos = scheduleSiteDao.getScheduleVideoStatus(ids);
                for (ScheduleRecord scheduleRecord:list){
                    if (videos.size()>0){
                        for (ScheduleVideo video : videos) {
                            if (scheduleRecord.getRecordID().equals(video.getAppointmentID())){
                                scheduleRecord.setVideoStatus(video.getVideoStatus());
                            }
                        }
                    }
                    scheduleRecords.add(scheduleRecord);
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return scheduleRecords;
    }

    public List<String> getAppointIdS(List<ScheduleRecord>  schedules){
        List<String> appIdList=new ArrayList<String>();
        for (ScheduleRecord s:schedules) {
            String recordID = s.getRecordID();
            appIdList.add(recordID);
        }
        return appIdList;
    }

    @Override
    public Boolean addAppointFileMess(AppointFileMess param) {
        String[] urls = param.getUploudUrl().split(",");
        Boolean b=true;
        for (int i=0;i<urls.length;i++){
            Boolean bool=cloudAppDao.addAppointFileMess(param,urls[i]);
            b=b&&bool;
        }
        return b;
    }


    @Override
    public List<UrlMess> queryUrl(Map<String, String> map) {
        String paramstr=" where 1=1 ";
        if(StringUtils.isNotBlank(map.get("hosCode"))){
            paramstr+=" and hospitalCode='"+map.get("hosCode")+"'";
        }
        if(StringUtils.isNotBlank(map.get("patientName"))){
            paramstr+=" and patientName='"+map.get("patientName")+"'";
        }
        if(StringUtils.isNotBlank(map.get("identifyNo"))){
            paramstr+=" and identifyNo='"+map.get("identifyNo")+"'";
        }
        if(StringUtils.isNotBlank(map.get("cardNo"))){
            paramstr+=" and cardNo='"+map.get("cardNo")+"'";
        }
        if(StringUtils.isNotBlank(map.get("doctorName"))){
            paramstr+=" and doctorName='"+map.get("doctorName")+"'";
        }
        if(StringUtils.isNotBlank(map.get("startTime"))){
            paramstr+=" and createTime>'"+map.get("startTime")+"'";
        }
        if(StringUtils.isNotBlank(map.get("endTime"))){
            paramstr+=" and createTime<"+"DATE_ADD('"+map.get("endTime")+"',INTERVAL 1 DAY)";
        }
        List<UrlMess> list=cloudAppDao.queryUrl(paramstr);
        return list;
    }

    @Override
    public Map<String, Object> addDocmess(String hosCode,String hosName,String idCard, String workNum) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            //查询医生logicId等基础信息
            URL u = new URL(ResultCode.userMess);
            Map m = new HashMap();
            m.put("logic","And");
            m.put("identifyNo",idCard);
            List<UserMess> userMessList = new ArrayList<UserMess>();
            Object obj = HttpUtilsKt.postJson(u, m, JsonExtKt.getListJavaType(Reflection.getOrCreateKotlinClass(Object.class)));
            String json = JSON.toJSON(obj).toString();
            userMessList = JSONArray.parseArray(json, UserMess.class);
            if(userMessList==null||userMessList.size()==0){
                map.put("code",ResultCode.ERROR);
                map.put("msg","此身份证未注册捷医，请先去注册");
                return map;
            }
            //根据工号和医院代码确认具体所属科室等
            URL u2 = new URL(ResultCode.doctorWork);
            Map m2 = new HashMap();
            m2.put("hospitalCode",hosCode);
            List<DoctorMess> docMessList = new ArrayList<DoctorMess>();
            Object obj2 = HttpUtilsKt.postJson(u2, m2, JsonExtKt.getListJavaType(Reflection.getOrCreateKotlinClass(Object.class)));
            String json2 = JSON.toJSON(obj2).toString();
            docMessList = JSONArray.parseArray(json2, DoctorMess.class);
            if(docMessList==null||docMessList.size()==0){
                map.put("code",ResultCode.ERROR);
                map.put("msg","未查询到此医院下医生信息");
                return map;
            }
            DoctorMess dmess=null;
            //查询医院编码与云诊室代码信息
            ArrayList<String> departList = cloudAppDao.findDepartListByCode(hosCode);
            for (DoctorMess dm:docMessList) {
                if(hosCode.equals(dm.getHospitalCode())&&workNum.equals(dm.getDoctorNo())&&departList.contains(dm.getDepartmentCode())){
                    dmess=dm;
                    break;
                }
            }
            if(dmess==null){
                map.put("code",ResultCode.ERROR);
                map.put("msg","未查询到此医生工号对应相关科室信息");
                return map;
            }
            //将相关信息保存到自己数据库
            Boolean bool=cloudAppDao.addDocMess(hosCode,hosName,idCard,workNum,userMessList.get(0),dmess);
            if(bool){
                map.put("code",ResultCode.SUCCESS);
                map.put("msg","添加信息成功");
            }else{
                map.put("code",ResultCode.SUCCESS);
                map.put("msg","添加信息失败");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public List<HashMap<String, List<CloudDoctor>>> queryCloudDoctor(Map<String, String> map) {
        String paramstr=" where 1=1 ";
        String hospitalCode=map.get("hospitalCode");
        if(StringUtils.isNotBlank(hospitalCode)){
            paramstr+=" and hospitalCode='"+hospitalCode+"'";
        }
        List<CloudDoctor> list=cloudAppDao.queryCloudDoctor(paramstr);
        List<String> listcode=cloudAppDao.queryListcode(paramstr);
        ArrayList<HashMap<String, List<CloudDoctor>>> listall = new ArrayList<HashMap<String, List<CloudDoctor>>>();
        if(list!=null||list.size()>0){
            for (String code:listcode) {
                HashMap<String, List<CloudDoctor>> m = new HashMap<String, List<CloudDoctor>>();
                ArrayList<CloudDoctor> cloudDoctors = new ArrayList<CloudDoctor>();
                for (CloudDoctor cd:list) {
                    if(cd.getHospitalCode().equals(code)){
                        cloudDoctors.add(cd);
                    }
                    m.put(code,cloudDoctors);
                }
                listall.add(m);
            }
        }
        return listall;
    }

    public static void main(String[] args) {
        try {
            URL u = new URL(ResultCode.doctorWork);
            Map m = new HashMap();
            m.put("hospitalCode","42504704X00");
            List<DoctorMess> docMessList = new ArrayList<DoctorMess>();
            Object obj = HttpUtilsKt.postJson(u, m, JsonExtKt.getListJavaType(Reflection.getOrCreateKotlinClass(Object.class)));
            String json = JSON.toJSON(obj).toString();
            docMessList = JSONArray.parseArray(json, DoctorMess.class);
            if(docMessList==null||docMessList.size()==0){

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }


}
